package com.example.xplayer

import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.Surface
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.background
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Info
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import com.example.mediacore.player.AVPlayer
import com.example.mediacore.player.MediaInfo
import com.example.mediacore.player.PlayerState
import com.example.xplayer.ui.theme.XPlayerTheme

class PlayerActivity : ComponentActivity() {
    private val TAG: String = "PlayerActivity"
    private lateinit var player: AVPlayer
    private val testPlayUrl by lazy {
        "${Environment.getExternalStorageDirectory()}/Movies/559217460-1-192-180p.mp4"
    }

    // 仅保留UI所需的可观察状态
    private var playerState by mutableStateOf(PlayerState.IDLE)
    private var currentPosition by mutableLongStateOf(0L)
    private var errorMsg by mutableStateOf("")
    private var surfaceHolder: Surface? = null
    // 新增状态
    private var inputUrl by mutableStateOf(testPlayUrl) // URL输入框内容
    private var showInfoDialog by mutableStateOf(false) // 信息弹窗开关
    private var mediaInfo by mutableStateOf<MediaInfo?>(null) // 媒体信息

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        // 初始化播放器
        player = AVPlayer()
        setupPlayerListener()

        setContent {
            XPlayerTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    Column(
                        modifier = Modifier
                            .fillMaxSize()
                            .padding(innerPadding)
                            .verticalScroll(rememberScrollState())
                    ) {
                        PlayerAppContent(
                            inputUrl = inputUrl,
                            onUrlChanged = { inputUrl = it },
                            currentState = playerState,
                            errorMsg = errorMsg,
                            currentPosition = currentPosition,
                            mediaInfo = mediaInfo,
                            showInfoDialog = showInfoDialog,
                            onSurfaceReady = { surface ->
                                surfaceHolder = surface
                                player.init(inputUrl, surface) // 使用输入框URL
                            },
                            onSurfaceDestroy = {
                                surfaceHolder = null
                                player.pause()
                            },
                            onPrepare = {
                                player.init(inputUrl, surfaceHolder)    // 准备时获取输入框URL
                            },
                            onStart = { player.start() },
                            onPause = { player.pause() },
                            onStop = { player.stop() },
                            onSeek = { offsetMs ->
                                player.seekTo(currentPosition + offsetMs)
                            },
                            onShowInfo = {
                                player.getMediaInfo { info ->
                                    mediaInfo = info
                                    if (info == null) {
                                        Toast.makeText(
                                            this@PlayerActivity,
                                            "获取媒体信息失败",
                                            Toast.LENGTH_SHORT
                                        ).show()
                                    } else {
                                        showInfoDialog = true
                                    }
                                }
                            },
                            onDismissInfo = { showInfoDialog = false }
                        )
                    }
                }
            }
        }
    }

    // 仅处理状态更新和UI回调，不包含业务逻辑
    private fun setupPlayerListener() {
        player.setOnStateChangeListener { newState ->
            Log.d(TAG, "状态更新: ${newState.name}")
            playerState = newState
            if (newState != PlayerState.ERROR) {
                errorMsg = ""
            }
        }

        player.setOnErrorListener { code, msg ->
            errorMsg = "错误[$code]: $msg"
        }

        player.setOnProgressUpdateListener { currentUs ->
            currentPosition = currentUs
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        player.release()
    }
}

@Composable
private fun PlayerAppContent(
    inputUrl: String,
    onUrlChanged: (String) -> Unit,
    currentState: PlayerState,
    errorMsg: String,
    currentPosition: Long,
    mediaInfo: MediaInfo?,
    showInfoDialog: Boolean,
    onSurfaceReady: (Surface) -> Unit,
    onSurfaceDestroy: () -> Unit,
    onPrepare: () -> Unit,
    onStart: () -> Unit,
    onPause: () -> Unit,
    onStop: () -> Unit,
    onSeek: (Long) -> Unit,
    onShowInfo: () -> Unit,
    onDismissInfo: () -> Unit
) {
    val context = LocalContext.current
    val focusManager = LocalFocusManager.current
    val showToast = { msg: String ->
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
    }

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(12.dp),
        verticalArrangement = Arrangement.spacedBy(12.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        // 视频渲染区域
        VideoRenderArea(
            modifier = Modifier
                .fillMaxWidth()
                .aspectRatio(16f / 9f),
            onSurfaceReady = onSurfaceReady,
            onSurfaceDestroy = onSurfaceDestroy,
            currentState = currentState
        )

        // 错误信息展示
        if (errorMsg.isNotEmpty()) {
            Text(
                text = errorMsg,
                color = Color.Red,
                fontSize = 12.sp,
                modifier = Modifier
                    .fillMaxWidth()
                    .horizontalScroll(rememberScrollState()), // 启用横向滚动
                maxLines = 1 // 限制为单行，确保滚动效果正常
            )
        } else {
            Text(
                text = "当前进度: ${formatTime(currentPosition / 1000)}",
                color = Color.DarkGray,
                fontSize = 12.sp
            )
        }

        // 状态和路径展示
        Row (
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = "当前状态: ${currentState.name}",
                fontSize = 14.sp
            )
            Spacer(modifier = Modifier.width(2.dp))
            IconButton(
                onClick = onShowInfo,
                modifier = Modifier.size(14.dp)
            ) {
                Icon(
                    imageVector = Icons.Default.Info,
                    contentDescription = "显示媒体信息",
                    tint = Color.Black
                )
            }
        }

        // 控制按钮区域
        ControlButtonsArea(
            currentState = currentState,
            onPrepare = { onPrepare(); showToast("准备中") },
            onStart = { onStart(); showToast("开始播放") },
            onPause = { onPause(); showToast("已暂停") },
            onStop = { onStop(); showToast("已停止") },
            onSeekBack = { onSeek(-5000000); showToast("快退5秒") },
            onSeekForward = { onSeek(5000000); showToast("快进5秒") },
        )

        Spacer(modifier = Modifier.height(2.dp))

        // URL输入框
        UrlInputArea(
            inputUrl = inputUrl,
            onUrlChanged = onUrlChanged,
            onDone = { focusManager.clearFocus() }
        )

        // 信息弹窗
        if (showInfoDialog) {
            MediaInfoDialog(
                mediaInfo = mediaInfo,
                onDismiss = onDismissInfo
            )
        }
    }
}

// URL输入框组件
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun UrlInputArea(
    inputUrl: String,
    onUrlChanged: (String) -> Unit,
    onDone: () -> Unit
) {
    Column(modifier = Modifier.fillMaxWidth()) {
        Text("播放地址:", fontSize = 14.sp)
        Row(verticalAlignment = Alignment.CenterVertically) {
            TextField(
                value = inputUrl,
                onValueChange = onUrlChanged,
                modifier = Modifier.weight(1f),
                singleLine = false,
                maxLines = 2,
                textStyle = TextStyle(fontSize = 12.sp),
                keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
                keyboardActions = KeyboardActions(onDone = { onDone() }),
                placeholder = { Text("请输入视频地址", fontSize = 12.sp) }
            )
        }
    }
}

// 视频渲染区域
@Composable
private fun VideoRenderArea(
    modifier: Modifier,
    onSurfaceReady: (Surface) -> Unit,
    onSurfaceDestroy: () -> Unit,
    currentState: PlayerState
) {
    Box(modifier = modifier.background(Color.Black)) {
        AndroidView(
            factory = { context ->
                android.view.SurfaceView(context).apply {
                    layoutParams = android.view.ViewGroup.LayoutParams(
                        android.view.ViewGroup.LayoutParams.MATCH_PARENT,
                        android.view.ViewGroup.LayoutParams.MATCH_PARENT
                    )
                    holder.addCallback(object : android.view.SurfaceHolder.Callback {
                        override fun surfaceCreated(holder: android.view.SurfaceHolder) {
                            holder.surface?.let(onSurfaceReady)
                        }
                        override fun surfaceChanged(holder: android.view.SurfaceHolder, format: Int, width: Int, height: Int) {}
                        override fun surfaceDestroyed(holder: android.view.SurfaceHolder) = onSurfaceDestroy()
                    })
                }
            }
        )

        val hintText = when (currentState) {
            PlayerState.IDLE -> "点击准备加载视频"
            PlayerState.READY -> "准备就绪"
            PlayerState.ERROR -> "播放失败"
            else -> ""
        }
        if (hintText.isNotEmpty()) {
            Text(
                text = hintText,
                color = Color.White,
                modifier = Modifier.align(Alignment.Center)
            )
        }
    }
}

// 控制按钮区域
@Composable
private fun ControlButtonsArea(
    currentState: PlayerState,
    onPrepare: () -> Unit,
    onStart: () -> Unit,
    onPause: () -> Unit,
    onStop: () -> Unit,
    onSeekBack: () -> Unit,
    onSeekForward: () -> Unit
) {
    val canPrepare = currentState in listOf(PlayerState.IDLE, PlayerState.ERROR)
    val canStart = currentState in listOf(PlayerState.STOPPED, PlayerState.PAUSED, PlayerState.READY)
    val canPause = currentState == PlayerState.RUNNING
    val canStop = currentState in listOf(PlayerState.RUNNING, PlayerState.PAUSED)
    val canSeek = currentState in listOf(PlayerState.RUNNING, PlayerState.PAUSED)

    Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceEvenly
        ) {
            Button(onClick = onPrepare, enabled = canPrepare, modifier = Modifier.size(80.dp, 40.dp)) {
                Text("准备")
            }
            Button(onClick = onStart, enabled = canStart, modifier = Modifier.size(80.dp, 40.dp)) {
                Text("播放")
            }
            Button(onClick = onPause, enabled = canPause, modifier = Modifier.size(80.dp, 40.dp)) {
                Text("暂停")
            }
        }
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceEvenly
        ) {
            Button(onClick = onStop, enabled = canStop, modifier = Modifier.size(80.dp, 40.dp)) {
                Text("停止")
            }
            Button(onClick = onSeekBack, enabled = canSeek, modifier = Modifier.size(80.dp, 40.dp)) {
                Text("-5s")
            }
            Button(onClick = onSeekForward, enabled = canSeek, modifier = Modifier.size(80.dp, 40.dp)) {
                Text("+5s")
            }
        }
    }
}

// 媒体信息弹窗
@Composable
private fun MediaInfoDialog(mediaInfo: MediaInfo?, onDismiss: () -> Unit) {
    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("媒体详细信息") },
        text = {
            Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
                if (mediaInfo == null) {
                    Text("暂无媒体信息，请先准备播放")
                } else {
                    Text("起始时间: ${formatTime(mediaInfo.getStartPtsMs())}")
                    Text("总时长: ${formatTime(mediaInfo.getDurationMs())}")
                    Text("比特率: ${String.format("%.1f", mediaInfo.getBitRateKbps())}kbps")

                    Spacer(modifier = Modifier.height(8.dp))

                    if (mediaInfo.isAudioStream()) {
                        Text("===== 音频信息 =====")
                        Text("流索引: ${mediaInfo.getAudioStreamIdx()}")
                        Text("采样率: ${mediaInfo.getSampleRate()}Hz")
                        Text("声道数: ${mediaInfo.getAudioChannels()}")
                        Text("采样格式: ${mediaInfo.getSampleFormat()}")
                    }

                    if (mediaInfo.isVideoStream()) {
                        Text("===== 视频信息 =====")
                        Text("流索引: ${mediaInfo.getVideoStreamIdx()}")
                        Text("分辨率: ${mediaInfo.getResolution()}")
                        Text("帧率: ${mediaInfo.getFrameRate()}fps")
                        Text("像素格式: ${mediaInfo.getPixelFormat()}")
                    }
                }
            }
        },
        confirmButton = {
            Button(onClick = onDismiss) {
                Text("确认")
            }
        }
    )
}

// 时间格式化工具方法
private fun formatTime(milliseconds: Long): String {
    val totalSeconds = (milliseconds / 1000).toInt()
    val minutes = totalSeconds / 60
    val seconds = totalSeconds % 60
    return String.format("%02d:%02d", minutes, seconds)
}